package com.meituan.catering.management.product.dao.converter;

import com.meituan.catering.management.product.biz.model.request.SearchProductBizRequest;
import com.meituan.catering.management.product.dao.model.request.SearchProductDataRequest;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Believe
 * Date 2022/5/19 14:52
 */
public class SearchProductDataConverter {
    private static final String FUZZY_MATCH_PATTERN = "%{0}%";

    public static SearchProductDataRequest toSearchProductDataRequest(SearchProductBizRequest searchProductBizRequest) {
        if (searchProductBizRequest == null) {
            return null;
        }
        SearchProductDataRequest searchProductDataRequest = new SearchProductDataRequest();
        searchProductDataRequest.setPageIndex(searchProductBizRequest.getPageIndex() - 1);
        searchProductDataRequest.setPageSize(searchProductBizRequest.getPageSize());
        searchProductDataRequest.setName(MessageFormat.format(FUZZY_MATCH_PATTERN, searchProductBizRequest.getName()));
        searchProductDataRequest.setUnitOfMeasure(searchProductBizRequest.getUnitOfMeasure());
        searchProductDataRequest.setEnabled(searchProductBizRequest.getEnabled());
        searchProductDataRequest.setFrom(searchProductBizRequest.getFrom());
        searchProductDataRequest.setTo(searchProductBizRequest.getTo());
        searchProductDataRequest.setSortFields(toDataDOSort(searchProductBizRequest.getSortFields()));
        return searchProductDataRequest;
    }

    public static List<SearchProductDataRequest.SortField> toDataDOSort(List<SearchProductBizRequest.SortField> sortFields) {
        if (!sortFields.isEmpty()) {
            return null;
        }
        List<SearchProductDataRequest.SortField> sortFieldList = new ArrayList<>();
        SearchProductDataRequest.SortField enabledField = new SearchProductDataRequest.SortField("enabled", "desc");
        SearchProductDataRequest.SortField lastModifyField = new SearchProductDataRequest.SortField("last_modified_at", "desc");
        if (sortFields.isEmpty()) {
            sortFieldList.add(enabledField);
            sortFieldList.add(lastModifyField);
            return sortFieldList;
        }
        for (SearchProductBizRequest.SortField sortField : sortFields) {
            SearchProductDataRequest.SortField field = new SearchProductDataRequest.SortField();
            field.setField(sortField.getField());
            field.setAsc(sortField.getAsc());
            sortFieldList.add(field);
        }
        return sortFieldList;
    }

}
